package myclient;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
/**
 * @author JIAO
 */
public class ClientFileTransfer extends Thread{

	/**IP为IP地址，port为端口，or为接收端或发送端,name为文件名
	 */
	String ip;
	int port;
	int or;
	File name;
	int num;
	String talkToID;
	MainFrame mainFm;
	public ClientFileTransfer(String ip,int port,int or,File name,int num,String talkToID,MainFrame mainFm) {
		this.ip = ip;
		this.port = port;
		this.or = or;
		this.name = name;
		this.num = num;
		this.talkToID = talkToID;
		this.mainFm = mainFm;
	}
	public void run(){

		
		try {
			//建立连接
			Socket s = new Socket(ip,port);
			System.out.println(" or:"+or);
			if(or==0){	//此连接为接收方
				//接收用
				System.out.println("接收方连接上了");
				BufferedOutputStream out = new BufferedOutputStream(s.getOutputStream());
				out.write(num);
				out.flush();
				out.write(0);
				out.flush();
				byte[] buf = new byte[4096];
				int len=0;
				BufferedInputStream reader = new BufferedInputStream(s.getInputStream());
				BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(name));
				
				while((len=reader.read(buf))!=-1){
					writer.write(buf, 0, len);
					writer.flush();
				}
				writer.close();
				System.out.println("接收端接收完毕！");
				TalkFrame fm = mainFm.talkMap.get(talkToID); 
				fm.pnRight.remove(fm.pnMap.get(name.getName()));
				fm.pnMap.remove(name.getName());
				fm.fm.repaint();
				fm.area1.append("文件:"+name.getName()+"接收完毕\n");
				
				
			}else if(or==1){	//此连接为发送方
				//发送
				System.out.println("发送方方连接上了");
				byte[] buf = new byte[4096];
				int len=0;
				BufferedInputStream reader = new BufferedInputStream(new FileInputStream(name));
				BufferedOutputStream writer = new BufferedOutputStream(s.getOutputStream());
				writer.write(num);
				writer.flush();
				writer.write(1);
				writer.flush();
				while((len=reader.read(buf))!=-1){
					writer.write(buf, 0, len);
					writer.flush();
				}
				writer.close();
				System.out.println("传送段文件传输完毕！");
				mainFm.talkMap.get(talkToID).area1.append("文件:"+name.getName()+"传送完毕\n");
			}
			
		} catch (UnknownHostException e){
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	
	}
	public ClientFileTransfer(){}

}
